import { formatTime } from '@gnlab/utils'
import { useAsyncEffect } from '@gnlab/utils/env-react'
import { Spin, message, Table } from 'antd'
import { Modal } from '@/desktop/components'
import services from '@/services'
import type { MonitorApplyRecord } from '@/services/features/group-monitor-apply'
import { ApplyStatus } from '@/services/features/group-monitor-apply'
import './ApplyRecords.module.less'

export default function ApplyRecordsModal(props: {
  taskInfo: { taskId: number; qywxName: string } | null
  onClose: () => void
}) {
  const { taskInfo, onClose } = props

  return <Modal
    styleName="modal"
    title={taskInfo ? `${taskInfo.qywxName} 加人明细` : ''}
    footer={null}
    width="800px"
    open={!!taskInfo}
    onCancel={onClose}
  >
    {taskInfo ? <Content taskId={taskInfo.taskId} /> : null}
  </Modal>
}

function Content(props: { taskId: number }) {
  const { taskId } = props

  const [records, setRecords] = useState<MonitorApplyRecord[] | null>(null)
  useAsyncEffect(async () => {
    const res = await services.features.groupMonitorApply.loadApplyRecords(taskId)
    if (!res.success) void message.warning(`加人记录加载失败：${res.error}`)
    else setRecords(res.data)
  }, [])

  const renderJoined = useCallback(
    (record: MonitorApplyRecord) => formatTime(record.groupJoined),
    [],
  )
  const renderPassed = useCallback((record: MonitorApplyRecord) => {
    return record.applyPassed ? formatTime(record.applyPassed) : <div styleName="not-passed">/</div>
  }, [])
  const renderStatus = useCallback((record: MonitorApplyRecord) => {
    return record.status === ApplyStatus.Applyed ? (
      <span styleName="applyed">已申请</span>
    ) : (
      <span styleName="passed">通过</span>
    )
  }, [])

  if (!records)
    return <div styleName="loading">
      <Spin tip="加载中..." size="large" />
    </div>

  return <Table<MonitorApplyRecord>
    rowKey="wxid"
    dataSource={records}
    scroll={{ y: 500 }}
    pagination={false}
  >
    <Table.Column<MonitorApplyRecord> title="添加账号" dataIndex="contactName" width={200} />
    <Table.Column<MonitorApplyRecord> title="所属群聊" dataIndex="groupName" width={120} />
    <Table.Column<MonitorApplyRecord>
      title="进群时间"
      width={120}
      align="center"
      render={renderJoined}
    />
    <Table.Column<MonitorApplyRecord>
      title="通过时间"
      width={120}
      align="center"
      render={renderPassed}
    />
    <Table.Column<MonitorApplyRecord> title="状态" width={120} render={renderStatus} />
  </Table>
}
